var graph = new joint.dia.Graph;
joint.shapes.standard.Link.define('app.Link', {
    router: {
        name: 'normal'
    },
    labels: [],
    attrs: {
        line: {
            stroke: '#20C1DD',
            strokeDasharray: '0',
            strokeWidth: 2,
            fill: 'none',
            sourceMarker: {
                type: 'path',
                d: 'M 0 0 0 0',
                stroke: 'none'
            },
            targetMarker: {
                type: 'path',
                d: 'M 0 -5 -10 0 0 5 z',
                stroke: 'none'
            }
        }
    }
}, {

    getMarkerWidth: function(type) {
        var d = (type === 'source') ? this.attr('line/sourceMarker/d') : this.attr('line/targetMarker/d');
        return this.getDataWidth(d);
    },

    getDataWidth: _.memoize(function(d) {
        return (new g.Path(d)).bbox().width;
    })

}, {

    connectionPoint: function(line, view, magnet, opt, type, linkView) {
        var markerWidth = linkView.model.getMarkerWidth(type);
        opt = { offset: markerWidth, stroke: true };
        // connection point for UML shapes lies on the root group containg all the shapes components
        if (view.model.get('type').indexOf('uml') === 0) opt.selector = 'root';
        return joint.connectionPoints.boundary.call(this, line, view, magnet, opt, type, linkView);
    }
});
var paper = new joint.dia.Paper({
    width: 2000,
    height: 1500,
    model: graph,
    gridSize: 1,
    snapLinks: true,
    linkPinning: false,
    defaultLink: new joint.dia.Link({
        // router: { name: 'manhattan' },
        //    connector: { name: 'rounded' },
        smooth: true,
        attrs: {
            '.connection': {
                stroke: '#20C1DD',
                'stroke-width': 2,
                //  'stroke-dasharray': '5 2',
                pointerEvents: 'none',
            },
            '.marker-target': {
                fill: '#20C1DD',
                stroke: '#fff',
                d: 'M 10 0 L 0 5 L 10 10 z'
            }
        },
    }),
    defaultConnectionPoint: joint.shapes.app.Link.connectionPoint
});
//paper背景
var bgimage = '';
paper.drawBackground({
    image : bgimage
});

//控制纸张
var paperScroller = new joint.ui.PaperScroller({
    paper: paper,
    autoResizePaper: true,
    padding: 50,
    cursor: 'grab'
});
// 移动纸张
paper.on('blank:pointerdown', paperScroller.startPanning);
$('#paper').append(paperScroller.render().el);
paperScroller.center();    //移动到页面的中间


var commandManager = new joint.dia.CommandManager({
    graph: graph
});


new joint.ui.Tooltip({
    rootTarget: document.body,
    target: '[data-tooltip]',
    padding: 15
});


//鹰眼开始
var nav = new joint.ui.Navigator({
    paperScroller: paperScroller,
    width: 133,
    height: 100,
    padding: 5,
    model: graph,
    gridSize: 1,
//        zoomOptions: { max: 2, min: 0.12 }
});
nav.$el.appendTo('#myholder-small');
nav.render();
//小图结束


//tooltip模块
new joint.ui.Tooltip({
    target: '[data-tooltip]',
    rootTarget: document.body,
    direction: 'auto',
    padding: 15,
});

var resourceAllField;//初始对象的所有字段 (表格所用)
var resourceObjId= $('base').attr('objectid'); //初始对象id(cell.id)
var resourceObj; //初始对象(cell)
var resourceResult; //初始对象的json数据(result)


//单击元素
paper.on('cell:pointerclick',function(cellView){
       console.log(cellView.model);
    if(cellView.model.attributes.type === 'basic.TextBlock' && cellView.model.attributes.attrs.vertexType !== "transColumn") {
        var  halo = new joint.ui.Halo({ cellView: cellView});
        //元素只连接元素
        halo.on('action:link:add', function(link) {
            if (!link.get('source').id || !link.get('target').id) {
                link.remove();
            }
        });
        halo.render();
        halo.removeHandles();

        if(cellView.model.attributes.attrs.isRightOpen) {       //判断是否展开，右边icon状态
            halo.addHandle({ name: 'myaction', position: 'ne', icon: '/assets/custom/draw/img/wancheng.svg' });
        }else {
            halo.addHandle({ name: 'myaction', position: 'ne', icon: '/assets/custom/draw/img/zhankai.svg' });
        }

        if(cellView.model.attributes.attrs.isLeftOpen) {       //判断是否展开，右边icon状态
            halo.addHandle({ name: 'myactionleft', position: 'nw', icon: '/assets/custom/draw/img/wancheng.svg' });
        }else {
            halo.addHandle({ name: 'myactionleft', position: 'nw', icon: '/assets/custom/draw/img/zhankai.svg' });
        }

        //halo插件的tooltip
        halo.changeHandle('myaction', {
            attrs: {
                '.handle': {
                    'data-tooltip-class-name': 'small',
                    'data-tooltip': '影响',
                    'data-tooltip-position': 'left'
                }
            }
        });
        halo.changeHandle('myactionleft', {
            attrs: {
                '.handle': {
                    'data-tooltip-class-name': 'small',
                    'data-tooltip': '溯源',
                    'data-tooltip-position': 'right'
                }
            }
        });
        //点击自定义图标

        halo.on('action:myaction:pointerdown', function(evt) {
            evt.stopPropagation();
            //判断是否向右展开
            if(!cellView.model.attributes.attrs.isRightOpen){    //如果没有展开

                cellView.model.attributes.attrs.isRightOpen = true;
                requestTable(cellView.model.id,'after',{isRightOpen:true});
                halo.changeHandle('myaction', { icon: '/assets/custom/draw/img/wancheng.svg' });
                showTable(cellView.model,{outbound:true},'right');
            }
        });
        halo.on('action:myactionleft:pointerdown', function(evt) {
            evt.stopPropagation();
            //判断是否向左展开
            if(!cellView.model.attributes.attrs.isLeftOpen){    //如果没有展开

                cellView.model.attributes.attrs.isLeftOpen = true;
                requestTable(cellView.model.id,'before',{isLeftOpen:true});
                halo.changeHandle('myactionleft', { icon: '/assets/custom/draw/img/wancheng.svg' });
                showTable(cellView.model,{inbound:true},'left');
            }
        });

    }

});


//右键点击元素
/*paper.on('cell:contextmenu',function(cellView,evt,x,y){

    if(cellView.model.attributes.type === "basic.TextBlock"){
        var fa_item_ul = $('<ul class="vakata-context jstree-contextmenu jstree-default-contextmenu item_ul"></ul>');
        var  fa_item_li = ['打开','浏览数据','SQL','创建交换流程（以本对象为输入）','创建交换流程（以本对象为输出'];  //一级的li
        var e = evt || window.evt;

        $.each(fa_item_li,function (i, v) {
            fa_item_ul.append('<li class=""><a class="" href="#">'+v+'</a></li>')
        });

        fa_item_ul.appendTo($('#app'));
        $('.item_ul').css({'display':'block','position':'absolute','z-index':'1000','background':'#fff','left':''+(e.clientX+10)+'px','top':''+(e.clientY+10)+'px'});
    }


});*/
//右键删除列表
paper.on('blank:contextmenu',function(){
    $('.item_ul').remove()
});

//点击document删除列表
$(document).click(function(e){
    var tar = $(e.target);
    if(!tar.hasClass('erFisrtMenu')){
        $('.item_ul').remove()
    }
});

//双击元素
paper.on('cell:pointerdblclick',function(cellView){
    if(cellView.model.attributes.attrs.firstId){
    	console.log(resourceObj.attributes.position)
    	resourcefieldId = cellView.model.id;
        layer.open({
            title : '请选择字段',
            type : 2,
            area : ["600px","400px"],
            content: '/browser/fieldChange'
        })
    }
});
//初始化首个对象
$.ajax({
	 url : '/rest/columnRelation/columnRelation',
    type : 'GET',
   dataType : 'JSON',
   data:{"id":resourceObjId},
   success: function(result){
	   console.log(result)
   	resourceResult = result; //初始对象的json数据(result)
   	renderInt(resourceResult,{position:{x:500,y:500},i:0}) //请求数据
   	paperScroller.centerContent(); //元素视角居中
   }
})

//请求首个数据
function renderInt(result,opts){
	var tableObj //当前元素
	  $.each(result.object.vertexs,function (i, v) {
        	resourceAllField = v.columns; //所有字段
             tableObj = new joint.shapes.basic.TextBlock({
                position : opts.position,
                id:v.columns[opts.i].columnId,
                size : v.vertexType !== 'transColumn'?{width : 180, height  : 90}:{width : 180, height  : 60},
                attrs : {
                    "vertexType" : v.vertexType,
                    "firstId":v.vertexId === resourceObjId?true:false,
                    'rect': {
                        fill: '#4c87b9',
                        stroke:'#4c87b9',
                        'follow-scale':true,
                    },
                    'fieldId':v.columns[opts.i].columnId,
                    'isRightOpen' : '',
                    'isLeftOpen' : '',
                    'div' : {
                    }
                }
            });
             
             var objectChname = v.objectChname?v.objectChname:"";
             var tableName = v.tableName?v.tableName:"";
             var executeSql = v.executeSql?v.executeSql:"";
             var columnChname = v.columns[opts.i].columnChname?v.columns[opts.i].columnChname:"";
             var columnName = v.columns[opts.i].columnName?v.columns[opts.i].columnName:"";
             
            if(v.vertexType === 'dataobj'){
                tableObj.attributes.attrs.div.html = '<div title="'+objectChname + '《'+tableName + '》'+'" class="TextBlockInfo"><p>'+objectChname+'</p><p>'+ '《'+v.tableName + '》' +'</p> </div> <p class="erFieldInfo" title="'+columnChname + '('+columnName+')'+'"> '+columnChname + '('+columnName+')'+' </p>';
            }else if(v.vertexType === 'sqlColumn') {
                tableObj.attributes.attrs.div.html = '<div title="'+objectChname + '《'+executeSql + '》'+'" class="TextBlockInfo"><p><i style="margin-right: 5px;" class=" iconfont icon-SQL"></i>'+objectChname+'</p><p>'+'《'+executeSql + '》'+'</p> </div> <p class="erFieldInfo" title="'+columnChname + '('+columnName+')'+'"> '+columnChname + '('+columnName+')'+' </p>';
            }else if(v.vertexType === 'transColumn'){
                tableObj.attributes.attrs.div.html = '<div class="TextBlockInfo"><p>临时字段</p></div> <p class="erFieldInfo" title="'+columnChname + '('+columnName+')'+'"> '+columnChname + '('+columnName+')'+' </p>';
            }

    });
	  
	  graph.addCell(tableObj) //渲染
	
  //第一个元素高亮设置
  resourceObj = graph.getElements()[0]; //第一个元素
  var ele =paper.findViewByModel(resourceObj); //cellView
  ele.highlight(null, {
      highlighter: {
          name: 'stroke',
          options: {
              padding: 6,
              rx: 3,
              ry: 3,
              attrs: {
                  'stroke-width': 3,
                  stroke: '#D05454'
              }
          }
      }
  });
}

//请求表和流程数据封装
function requestTable(requestId,forward,isOpen) {
    $.ajax({
        url : '/rest/columnRelation/columnRelation',
        type : 'GET',
        dataType : 'JSON',
        data:{"id":requestId,"forward":forward},
        success: function (result) {
            //去除元素上多余的线
            var linklikeArr=[];
            $.each(result.object.lines,function (i, v) {
                var topThis = v;
                if(graph.getLinks().length > 0){
                    $.each(graph.getLinks(),function (i, v) {
                        if(v.attributes.source.id === topThis.from && v.attributes.target.id === topThis.to){
                            if(linklikeArr.indexOf(topThis) === -1 ){
                                linklikeArr.push(topThis)
                            }
                        }
                    });
                }
            });
            var  linkArr = array_diff(result.object.lines, linklikeArr);

            var elementlikeArr = [];
            $.each(result.object.vertexs,function (i, v) {
                var topThis = v;
                if(graph.getElements().length > 0){
                    $.each(graph.getElements(),function (i, v) {
                        if(v.attributes.id === topThis.vertexId){
                            if(elementlikeArr.indexOf(topThis) === -1 ){
                                elementlikeArr.push(topThis)
                            }
                        }
                    });
                }
            });
            var  elementArr = array_diff(result.object.vertexs, elementlikeArr);

            console.log(elementArr);
            //初始化元素
            var tableObjArr = [];
            $.each(elementArr,function (i, v) {
                if(v.vertexType === 'dataobj' || v.vertexType === 'sqlColumn' || v.vertexType === 'transColumn'){  //是对象获取sql

                    var tableObj = new joint.shapes.basic.TextBlock({
                       /* position : {
                            x : 500,
                            y : 500
                        },*/
                        id:v.columns[0].columnId,
                        size : v.vertexType !== 'transColumn'?{width : 180, height  : 90}:{width : 180, height  : 60},
                        attrs : {
                            "vertexType" : v.vertexType,
                            "firstId":v.vertexId === resourceObjId?true:false,
                            'rect': {
                                fill: '#4c87b9',
                                stroke:'#4c87b9',
                                'follow-scale':true,
                            },
                            'fieldId':v.columns[0].columnId,
                            'isRightOpen' : isOpen.isRightOpen,
                            'isLeftOpen' : isOpen.isLeftOpen,
                            'div' : {
                            }
                        }
                    });
                    
                    var objectChname = v.objectChname?v.objectChname:"";
                    var tableName = v.tableName?v.tableName:"";
                    var executeSql = v.executeSql?v.executeSql:"";
                    var columnChname = v.columns[0].columnChname?v.columns[0].columnChname:"";
                    var columnName = v.columns[0].columnName?v.columns[0].columnName:"";
                    
                    if(v.vertexType === 'dataobj'){
                        tableObj.attributes.attrs.div.html = '<div title="'+objectChname + '《'+tableName + '》'+'" class="TextBlockInfo"><p>'+objectChname+'</p><p>'+ '《'+tableName + '》' +'</p> </div> <p class="erFieldInfo" title="'+columnChname + '('+columnName+')'+'"> '+columnChname + '('+columnName+')'+' </p>';
                    }else if(v.vertexType === 'sqlColumn') {
                        tableObj.attributes.attrs.div.html = '<div title="'+objectChname + '《'+executeSql + '》'+'" class="TextBlockInfo"><p><i style="margin-right: 5px;" class=" iconfont icon-SQL"></i>'+objectChname+'</p><p>'+'《'+executeSql + '》'+'</p> </div> <p class="erFieldInfo" title="'+columnChname + '('+columnName+')'+'"> '+columnChname + '('+columnName+')'+' </p>';
                    }else if(v.vertexType === 'transColumn'){
                        tableObj.attributes.attrs.div.html = '<div class="TextBlockInfo"><p>临时字段</p></div> <p class="erFieldInfo" title="'+columnChname + '('+columnName+')'+'"> '+columnChname + '('+columnName+')'+' </p>';
                    }
                    tableObjArr.push(tableObj);
                }else if(v.vertexType === 'sql' || v.vertexType === 'trans'){                 //是交换流程
                    var objImg = new joint.shapes.basic.Image({
                        "size":{"width":40,"height":40},
                        "angle":0,
                        "id":v.vertexId,
                        "description":"image",
                        "z":1,
                        "attrs":{
                            "text":{"text":v.name?v.name:'',"ref-y":-5},
                            "image":{
                                "width":40,"height":40,
                                "class":"TU",
                                "vertexType" : v.vertexType,
                                "href":v.vertexType === 'sql'?"/assets/custom/draw/img/sql.svg":"/assets/custom/draw/img/TU.png",
                            }
                        }
                    });
                    tableObjArr.push(objImg);
                }

            });

            if(result.object.lines.length > 0){
                console.log(linkArr);
               
                $.each(linkArr,function (i, v) {
                    var link = new joint.shapes.app.Link({
                        "source":{"id":v.from},
                        "target":{"id":v.to},
                        smooth: true,
                        "id":v.lineId,
                        "attrs":{
                            ".connection":{"stroke":"#20C1DD","stroke-width":2,"pointerEvents":"none"},
                            ".marker-target":{"fill":"#20C1DD","stroke":"#20C1DD","d":"M 10 0 L 0 5 L 10 10 z"},
                        }
                        ,
                        "labels": [
                            {"position": 0.5, "attrs": {"text": {"text": v.exp ? v.exp :""}}}
                        ],
                        '.tool-remove' : null
                    });

                    tableObjArr.push(link)
                });
            }
            //添加元素
            graph.addCell(tableObjArr);
            console.log(graph.getLinks());
            //页面元素布局
            joint.layout.DirectedGraph.layout(graph, {
                setLinkVertices: false,
                marginX: 500,
                marginY: 500,
                rankSep : 150,
                rankDir: "LR",
                ranker : '500px'
            });
            
          /*  var graphLayout = new joint.layout.TreeLayout({
                graph: graph,
                parentGap: 80,
                siblingGap: 60
            });

            graphLayout.layout();*/
            
        },
        error : function (result) {
            layer.msg('加载失败')
        }
    });
}


//当前元素的所有源溯或者影响展开
function showTable(currentElement,obj,direction) {
    var list = [];  //元素id数组
    list.push(currentElement.id); //排除当前元素
    findRelateModel(currentElement);
    console.log(list);
    function findRelateModel(currentElement){     //子元素相关的所有元素
        var NeighborsBPMNArr = graph.getNeighbors(currentElement,obj);  //相邻元素数组
        $.each(NeighborsBPMNArr,function(i,v){        //遍历相关元素
            if(list.indexOf(v.id) === -1){
                list.push(v.id);
                console.log(list);
                if(direction === 'left'){
                    v.attributes.attrs.isLeftOpen = true;
                }else {
                    v.attributes.attrs.isRightOpen = true;
                }
                findRelateModel(v);               //回调
            }
        })


    }
}

//递归函数
function recursion(currentElement) {
    var list = [],eleList=[];  //元素id数组
    list.push(currentElement.id); //排除当前元素
    findRelateModel(currentElement);

    $.each(eleList,function (i, v) { //删除其他所有的元素
        v.remove();
    });
    joint.ui.Halo.clear(paper); //隐藏halo组件;
    function findRelateModel(currentElement){     //子元素相关的所有元素
        var NeighborsBPMNArr = graph.getNeighbors(currentElement);  //相邻元素数组
        $.each(NeighborsBPMNArr,function(i,v){        //遍历相关元素
            if(list.indexOf(v.id) === -1){
                list.push(v.id);
                eleList.push(v);
                findRelateModel(v);               //回调
            }
        });
    }
}

//两个数组不同的部分
function array_diff(a, b) {
    for(var i=0;i<b.length;i++)
    {
        for(var j=0;j<a.length;j++)
        {
            if(a[j]==b[i]){
                a.splice(j,1);
                j=j-1;
            }
        }
    }
    return a;
}



